<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bluetooth Devices</title>
</head>
<body>
<h1>Bluetooth Devices</h1>
<button id="scanButton" onclick="main()">Scan for Bluetooth Devices</button>
<ul id="deviceList"></ul>

<script>

    const service_uuid      = 'f0080001-0451-4000-b000-000000000000';
    const char_read_uuid    = 'f0080002-0451-4000-b000-000000000000';
    const char_uuid         = 'f0080003-0451-4000-b000-000000000000';
    const desc_uuid         = '00002902-0000-1000-8000-00805f9b34fb';

    async function requestDevice() {
        try {
            const device = await navigator.bluetooth.requestDevice({
                filters: [{
                    services: ["0000fee7-0000-1000-8000-00805f9b34fb"]
                }],
                optionalServices: [service_uuid, char_uuid, char_read_uuid, desc_uuid]
            });
            return device;
        } catch (error) {
            console.error('Error requesting device:', error);
        }
    }

    async function connectDevice(device) {
        try {
            const server = await device.gatt.connect();
            return server;
        } catch (error) {
            console.error('Error connecting to device:', error);
        }
    }

    async function getServiceAndCharacteristic(server, service_uuid, char_uuid) {
        try {
            const service = await server.getPrimaryService(service_uuid);
            const characteristic = await service.getCharacteristic(char_uuid);
            return characteristic;
        } catch (error) {
            console.error('Error getting service and characteristic:', error);
        }
    }

    async function readData(characteristic) {
        try {
            const value = await characteristic.readValue();
            const decoder = new TextDecoder('utf-8');
            console.log('Received data:', decoder.decode(value));
        } catch (error) {
            console.error('Error reading data:', error);
        }
    }

    async function sendData(characteristic, data) {
        try {
            const encoder = new TextEncoder('utf-8');
            const value = encoder.encode(data);
            await characteristic.writeValue(value);
            console.log('Data sent:', data);
        } catch (error) {
            console.error('Error sending data:', error);
        }
    }

    async function main() {
        const device = await requestDevice();
        if (device) {
            const server = await connectDevice(device);

            const characteristic = await getServiceAndCharacteristic(server, service_uuid, char_read_uuid);
            const characteristic1 = await getServiceAndCharacteristic(server, service_uuid, char_uuid);
            const desc = await characteristic.getDescriptor(desc_uuid)

            characteristic.addEventListener('characteristicvaluechanged', handleChanged);
            characteristic1.addEventListener('characteristicvaluechanged', handleChanged_1);

            characteristic.startNotifications();
            // characteristic1.startNotifications();

            //const hexNumbers1 = ['0x00']
            //const uint8Array1 = new Uint8Array(hexNumbers1.map(hex => parseInt(hex, 16)));
            //desc.writeValue(uint8Array1)
            // const desc_value = await desc.readValue()
            // console.log(desc_value)

            const year1 = yearToHex(new Date().getFullYear()).substring(0, 2)
            const year2 = yearToHex(new Date().getFullYear()).substring(2, 4)

            const hexNumbers = [
                '0xA1',
                '0x00',
                '0x00',
                '0x00',
                '0x' + year1,
                '0x' + year2,
                '0x' + monthToHex(new Date().getMonth() + 1),
                '0x' + convertDayToHexString(new Date().getDate()),
                '0x' + hourToHexString(new Date().getHours()),
                '0x' + minuteToHexString(new Date().getMinutes()),
                '0x' + minuteToHexString(new Date().getSeconds()),
                '0x00',
                '0x01'
            ]
            const uint8Array = new Uint8Array(hexNumbers.map(hex => parseInt(hex, 16)));
            characteristic1.writeValue(uint8Array)

            setTimeout(()=>{
                const hexNumbers1 = ['0xA8', '0x00']
                const uint8Array1 = new Uint8Array(hexNumbers1.map(hex => parseInt(hex, 16)));
                characteristic1.writeValue(uint8Array1)
            }, 1000)

            // await characteristic.startNotifications();


            // Send data
            //await sendData(characteristic, 'A800');

            // Read data
            //await readData(characteristic);

            // Optionally, disconnect from the device
            //server.disconnect();
        }
    }

    function handleChanged(event) {
        console.log('--------------')
        console.log('read:', event.target.value);
    }

   function handleChanged_1(event) {
        console.log('--------1------')
        console.log('read:', event.target.value);
    }
	
    function yearToHex(year) {
        if (typeof year !== 'number' || isNaN(year)) {
            throw new Error('Invalid year number');
        }

        // Convert to hexadecimal and pad with leading zeros to 4 digits
        return year.toString(16).toUpperCase().padStart(4, '0');
    }

    function monthToHex(month) {
        if (month < 1 || month > 12) {
            throw new Error("Month must be between 1 and 12.");
        }
        // Convert to hex and ensure it's two characters long
        const hexString = month.toString(16).padStart(2, '0');
        return hexString;
    }

    function convertDayToHexString(day) {
        // Convert the day to a hexadecimal string
        var hexString = day.toString(16);

        // If the resulting string has only one digit, prepend a '0' to make it two digits
        if (hexString.length === 1) {
            hexString = '0' + hexString;
        }

        return hexString;
    }

    function hourToHexString(hour) {
        var hexString = hour.toString(16);
        return hexString.length === 1 ? "0" + hexString : hexString;
    }

    function minuteToHexString(minute) {
        var hexString = minute.toString(16);
        return hexString.length === 1 ? "0" + hexString : hexString;
    }
</script>
</body>
</html>